﻿using System.Linq;
using Enyim.Caching;
using Ayatta.Contract;
using Web.Pay.Models;
using System.Web.Mvc;
using Web.Base.Security;
using System.Configuration;
using Web.Base.Components;
using Ayatta.Contract.Domain;
using System.Collections.Generic;
using Ayatta.Contract.Component;

namespace Web.Pay.Controllers
{
    public class OrderController : PayBaseController
    {
        protected static readonly string PasswordSalt = ConfigurationManager.AppSettings["Password.Salt"];

        public OrderController(ILogService logService, IBaseService baseService, IExtraService extraService, IStoreService storeService, IOrderService orderService, IGameService gameService, IAuctionService auctionService, IPassportService passportService, IPaymentService paymentService, IMemcachedClient memcachedClient)
            : base(logService, baseService, extraService, storeService, orderService, gameService, auctionService, passportService, paymentService, memcachedClient)
        {
        }

        /// <summary>
        /// 网购订单
        /// </summary>
        /// <param name="param">订单Id</param>
        /// <returns></returns>
        public ActionResult Index(string param)
        {
            var identity = User.Identity.Identity();
            var model = new OrderControllerModel.Index();
            var trade = PaymentService.GetUserTrade(param, identity.Id);
            if (trade != null)
            {
                if (trade.Status == UserTradeStatus.Pending)
                {
                    var platforms = GetAllPaymentPlatform();
                    var tmpEBanks = PaymentService.GetAllPaymentEBank(null, true);

                    var eBanks = new List<PaymentEBank>();
                    foreach (var platform in platforms)
                    {
                        var p = platform;
                        var x = eBanks.Select(o => o.BankId);
                        var tmp = tmpEBanks.Where(o => o.PlatformId == p.Id && !x.Contains(o.BankId));
                        eBanks.AddRange(tmp.SkipWhile(o => !o.Status));
                    }
                    model.Trade = trade;

                    model.Account = PaymentService.GetUserAccount(identity.Id);
                    model.Order = OrderService.GetOrder(param, identity.Id);
                    model.Platforms = platforms;
                    model.EBanks = eBanks;
                }
                else
                {
                    var url = WebSite.My + "/order/detail/" + param;
                    return Redirect(url);
                }
            }
            else
            {
                var url = WebSite.My + "/order/pay/" + param;
                return Redirect(url);
            }
            return View(model);
        }

        /// <summary>
        /// 使用余额支付
        /// </summary>
        /// <param name="param">订单号</param>
        /// <param name="password">支付密码</param>
        /// <returns></returns>
        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult Balance(string param, string password)
        {
            var identity = User.Identity;
            var userId = identity.Identity().Id;
            var result = new SkResult<string>();
            var user = PassportService.GetUser(userId);
            if (user != null)
            {
                //var payPassword = (password.ToPassword() + PasswordSalt).ToPassword();
                //if (user.PayPassword != payPassword)
                //{
                //    result.Message = "支付密码不正确！";
                //    return Json(result);
                //}
                var trade = PaymentService.GetUserTrade(param, userId);
                if (trade.Status == UserTradeStatus.Pending || trade.Status == UserTradeStatus.WaitBuyerPay)
                {
                    var payTrade = trade.ToPayTrade(GetIpAddress());
                    var status = PaymentService.PayByBalance(payTrade);
                    if (status)
                    {
                        InternalOrderHandler(payTrade);
                    }
                    result.Status = status;
                }
                else
                {
                    result.Message = "支付密码不正确！";
                    return Json(result);
                }
            }
            return Json(result);
        }

        /// <summary>
        /// 支付交易
        /// </summary>
        /// <param name="param">交易Id</param>
        /// <returns></returns>
        public ActionResult Trade(string param)
        {
            return View();
        }
        [HttpPost]
        public ActionResult Trade(string param, int onlinePayment, bool balance, int? bank, int? platform)
        {
            /*
             付款方式多种多样，货到付款，网上支付，邮局汇款，银行转帐，帐户余额支付，支票支付。
            Payment methods varied, Delivery, online payment, post office remittances, bank transfer, account balance of payments, Dangdang honor card payment by cheque
             */

            var url = DefaultUrl;
            var identity = User.Identity.Identity();
            var order = OrderService.GetOrder(param, identity.Id);
            // if(order.PaymentStatus==)
            var account = PaymentService.GetUserAccount(identity.Id);


            var pay = GetOnlinePay(bank.Value);

            if (pay != null)
            {

                var trade = new PayTrade();
                url = pay.GetPayUrl(trade);
                return Redirect(url);
            }
            return Redirect(url);
        }
    }
}
